﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using System.Threading;

namespace BaseHelper.Base
{
    public class ImageHelper
    {
        public struct ColorData
        {
            public string ColorHex;
            public Color NewColor;
        }

        public static Image ToImage(string base64String)
        {
            try
            {
                byte[] base64Bytes = Convert.FromBase64String(base64String);
                MemoryStream memoryStream = new MemoryStream(base64Bytes);
                return Image.FromStream(memoryStream);
            }
            catch(Exception ex)
            {
                LogHelper.Err("BaseHelper.Base.ImageHelper.cs", "ToImage(string base64String)", ex);
            }
            return null;
        }

        public static Image ToImage(byte[] bytes)
        {
            if (bytes == null)
                return null;

            try
            {
                MemoryStream memoryStream = new MemoryStream(bytes);
                return Image.FromStream(memoryStream);
            }
            catch (Exception ex)
            {
                LogHelper.Err("BaseHelper.Base.ImageHelper.cs", "ToImage(byte[] bytes)", ex);
            }
            return null;
        }

        public static string ToBase64(Image img)
        {
            return ToBase64(img, ImageFormat.Bmp);
        }

        public static string ToBase64(Image img,ImageFormat format)
        {
            if (img == null)
                return "";
            string ret = "";
            using (MemoryStream ms = new MemoryStream())
            {
                try
                {
                    img.Save(ms, format);
                    ret = Convert.ToBase64String(ms.ToArray());
                }
                catch (Exception ex)
                {
                    LogHelper.Err("BaseHelper.Base.ImageHelper.cs", "ToBase64(Image img,ImageFormat format)", ex);
                }
            }
            return ret;
        }

        public static byte[] ToBytes(Image imgPhoto,bool isBmp=false)
        {
            try
            {
                MemoryStream mstream = new MemoryStream();
                imgPhoto.Save(mstream, isBmp ? ImageFormat.Bmp : ImageFormat.Jpeg);
                byte[] byData = new Byte[mstream.Length];
                mstream.Position = 0;
                mstream.Read(byData, 0, byData.Length);
                mstream.Close();
                return byData;
            }
            catch (Exception ex)
            {
                LogHelper.Err("BaseHelper.Base.ImageHelper.cs", "ToBytes(Image imgPhoto)", ex);
            }
            return null;
        }

        public static byte[] ToBytes(Image img, ImageFormat format)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                img.Save(ms, format);
                return ms.ToArray();
            }
            catch (Exception ex)
            {
                LogHelper.Err("BaseHelper.Base.ImageHelper.cs", " ToBytes(Image img, ImageFormat format)", ex);
            }

            return null;

        }
        
        public static string ToThumbBase64(Image img)
        {
            return ToBase64(img, ImageFormat.Png);
        }

        public static Image GetThumb(Image bmp, int Width, int Height, bool IsHigh = false)
        {

            try
            {
                Image newimage = new Bitmap(Width, Height);
                Graphics newg = Graphics.FromImage(newimage);
                newg.InterpolationMode = IsHigh ? System.Drawing.Drawing2D.InterpolationMode.Default : System.Drawing.Drawing2D.InterpolationMode.Low;
                newg.SmoothingMode = IsHigh ? System.Drawing.Drawing2D.SmoothingMode.Default : System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
                newg.Clear(Color.White);
                newg.DrawImage(bmp, new Rectangle(0, 0, newimage.Width, newimage.Height), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                return newimage;
            }
            catch (Exception ex)
            {
                LogHelper.Err("BaseHelper.Base.ImageHelper.cs", "  GetThumb()", ex);
            }
            return null;
        }

        public static Image GetScreen()
        {
            try
            {
                Bitmap baseImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
                Graphics g = Graphics.FromImage(baseImage);
                g.CopyFromScreen(new Point(0, 0), new Point(0, 0), Screen.AllScreens[0].Bounds.Size);
                g.Dispose();
                return baseImage;
            }
            catch (Exception ex)
            {
                LogHelper.Err("BaseHelper.Base.ImageHelper.cs", "  GetScreen()", ex);
            }
            return null;

        }

        public static Bitmap ColorChange(Bitmap bmp,string SaveUpdateImage, List<ColorData> ltCD)
        {
            try
            {
                Graphics g = Graphics.FromImage(bmp);
                ImageAttributes attr = new ImageAttributes();

                List<ColorMap> ltColorMap = new List<ColorMap>();
                ColorMap colorMap;
                foreach (ColorData cd in ltCD)
                {
                    colorMap = new ColorMap();
                    colorMap.OldColor = ColorHexToRGB(255, cd.ColorHex);
                    colorMap.NewColor = cd.NewColor;
                    ltColorMap.Add(colorMap);
                   
                    //for (int i = 1; i <= 10; i++)
                    //{
                    //    ColorMap scolorMap = new ColorMap();

                    //    scolorMap.NewColor = cd.NewColor;

                    //    scolorMap.OldColor = ColorHexToRGB(255, cd.ColorHex, i);
                    //    ltColorMap.Add(colorMap);

                    //    scolorMap.OldColor = ColorHexToRGB(255, cd.ColorHex, -i);
                    //    ltColorMap.Add(colorMap);
                    //}
                }
                attr.SetRemapTable(ltColorMap.ToArray(), ColorAdjustType.Bitmap);

                Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                g.DrawImage(bmp, rect, 0, 0, rect.Width, rect.Height, GraphicsUnit.Pixel, attr);
                if (SaveUpdateImage != null)
                {
                    try
                    {
                        bmp.Save(SaveUpdateImage, ImageFormat.Png);
                    }
                    catch
                    {
                        Thread.Sleep(100);
                        try
                        {
                            bmp.Save(SaveUpdateImage, ImageFormat.Png);
                        }
                        catch (Exception ex2)
                        {
                            LogHelper.Err("Helper.Base.ImageHelper.cs", "ColorChange()", ex2);
                        }
                    }
                }
                return bmp;

            }
            catch (Exception ex)
            {
                LogHelper.Err("Helper.Base.ImageHelper.cs", "ColorChange()", ex);
            }
            return null;
        }

        public static Color ColorHexToRGB(int alpha, string strHxColor,int fix=0)
        {
            try
            {
                if (strHxColor.Length == 0)
                {
                    //如果为空
                    //设为黑色
                    return Color.FromArgb(0, 0, 0);
                }
                else
                {
                    int R=Int32.Parse(strHxColor.Substring(1, 2), NumberStyles.AllowHexSpecifier) + fix ;
                    int G=Int32.Parse(strHxColor.Substring(3, 2), NumberStyles.AllowHexSpecifier) + fix ;
                    int B=Int32.Parse(strHxColor.Substring(5, 2), NumberStyles.AllowHexSpecifier) + fix ;

                    R = R < 0 ? R = 0 : R > 255 ? 255 : R;
                    G = G < 0 ? G = 0 : G > 255 ? 255 : G;
                    B = B < 0 ? B = 0 : B > 255 ? 255 : B;

                    //转换颜色
                    return Color.FromArgb(alpha,R,G,B);
                }
            }
            catch
            {
                //设为黑色
                return Color.FromArgb(0, 0, 0);
            }
        }

        public static Image Image_Cut_Small(string FilePath, int X, int Y, int Width, int Height)
        {
            try
            {
                Bitmap src = (Bitmap)Image.FromFile(FilePath);
                if (src.Width == Width)
                    return src;

                Bitmap newBitmap = src.Clone(new Rectangle(X, Y, Width, Height), PixelFormat.DontCare);
                src.Dispose();
                newBitmap.Save(FilePath);
                return (Image)newBitmap;
            }
            catch { }

            return null;

        }

        public static Image Image_Cut_Small(Image image, int X, int Y, int Width, int Height)
        {
            try
            {
                Bitmap src = (Bitmap)image;
                if (src.Width == Width && src.Height==Height)
                    return src;

                Bitmap newBitmap = src.Clone(new Rectangle(X, Y, Width, Height), PixelFormat.DontCare);
                src.Dispose();
                return (Image)newBitmap;
            }
            catch { }

            return null;

        }

        public static bool Bmp32To24(string sourcePath, string savePath)
        {
            try
            {
                Bitmap bitmap = new Bitmap(sourcePath);
                Bitmap newbitmap = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), PixelFormat.Format24bppRgb);
                newbitmap.Save(savePath, ImageFormat.Bmp);
                newbitmap.Dispose();
                bitmap.Dispose();
                return true;
            }
            catch { }
            return false;
        }

        public static bool EncodingBmp(String sourcePath,string savePath, string type="jpg",int quality=100)
        {
            try
            {
                Bitmap bitmap = new Bitmap(sourcePath);
                ImageCodecInfo codecInfo = GetEncoderInfo("image/" + type);
                EncoderParameters parameters = new EncoderParameters(1);
                parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

                bitmap.Save(savePath, codecInfo, parameters);
                bitmap.Dispose();
                return true;
            }
            catch { }

            return false;

        }

        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }

    }
}
